package com.flower.handle.mybatispuls;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.flower.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.security.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            userId = -1L;//表示是自己创建
        }
        //处理时间问题
        Date time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            time = sdf.parse(sdf.format(System.currentTimeMillis()));
        } catch (ParseException e) {

        }

        this.setFieldValByName("createTime",time , metaObject);
        this.setFieldValByName("creator", userId.toString(), metaObject);
        this.setFieldValByName("updateTime", time, metaObject);
        this.setFieldValByName("recentLoginTime",time,metaObject);
        this.setFieldValByName("modifier", userId.toString(), metaObject);
        this.setFieldValByName("isDel", 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            time = sdf.parse(sdf.format(System.currentTimeMillis()));
        } catch (ParseException e) {

        }
        this.setFieldValByName("updateTime", time, metaObject);
        this.setFieldValByName("modifier", SecurityUtils.getUserId().toString(), metaObject);
    }
}